package cn.bdqn.filedemo01;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etFileName,etContent;
private Button btnWrite,btnWriteSD,btnRead,btnReadSD;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView(){
        etFileName=findViewById(R.id.et_fileName);
        etContent=findViewById(R.id.et_content);

        btnWrite=findViewById(R.id.btn_write);
        btnWriteSD=findViewById(R.id.btn_writeSD);
        btnRead=findViewById(R.id.btn_read);
        btnReadSD=findViewById(R.id.btn_readSD);

        btnWrite.setOnClickListener(this);
        btnWriteSD.setOnClickListener(this);
        btnRead.setOnClickListener(this);
        btnReadSD.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
          switch (v.getId()){
              case R.id.btn_write:
                  write();
                  break;
              case R.id.btn_writeSD:
                  writeSD();
                  break;
              case R.id.btn_read:
                  read();
                  break;
              case R.id.btn_readSD:
                  readSD();
                  break;
              default:break;

          }
    }
    //对存储卡进行操作
    private void write(){
        try {
            FileOutputStream fos=this.openFileOutput(etFileName.getText().toString(), Context.MODE_PRIVATE);
            fos.write(etContent.getText().toString().getBytes());
            fos.flush();
            fos.close();
            Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
            etContent.setText("");
        }  catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void read(){
        StringBuffer sb=new StringBuffer();
        try {
            FileInputStream fis=this.openFileInput(etFileName.getText().toString());
            byte[] buf=new byte[1024];
            int len=fis.read(buf);
            while (len!=-1){
                 sb.append(new String(buf,0,len));
                 buf=new byte[1024];
                 len=fis.read(buf);
            }
            fis.close();
            etContent.setText(sb.toString());
            Toast.makeText(this, "读取成功", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //调用回调函数
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
      switch (requestCode){
          case 1:
              if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                  //权限已申请成功
              }else {
                  //用户新建授权
                  Toast.makeText(this, "无法申请SD卡读写权限", Toast.LENGTH_SHORT).show();
                  finish();
              }
              break;
          default:super.onRequestPermissionsResult(requestCode, permissions, grantResults);
      }

    }


    //设置权限
    private void setPermission(){
        int permission_write= ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int permission_read=ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permission_write!= PackageManager.PERMISSION_GRANTED || permission_read!=PackageManager.PERMISSION_GRANTED){
            Toast.makeText(this, "正在啊请求权限", Toast.LENGTH_SHORT).show();
            //申请权限，持证码自定义为1,可在回调时进行相关判断
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},1);
        }

    }







    //对Sd卡进行操作，需要权限
    private void writeSD() {
        setPermission();
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this, "未找到SD卡", Toast.LENGTH_SHORT).show();
            return;
        }
        File file=new File(Environment.getExternalStorageDirectory()+"/"+etFileName.getText().toString());
        //异常捕捉ctrl+alt+t
        try {
            FileOutputStream fos=new FileOutputStream(file);
            fos.write(etContent.getText().toString().getBytes());
            fos.flush();
            fos.close();
            Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    private void readSD(){
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this, "未找到SD卡", Toast.LENGTH_SHORT).show();
            return;
        }
        StringBuffer sb=new StringBuffer();
       File file= new File(Environment.getExternalStorageDirectory()+"/"+etFileName.getText().toString());
        try {
           FileInputStream fis=new FileInputStream(file);
            byte[] buf=new byte[1024];
            int len=fis.read(buf);
            while (len!=-1){
                sb.append(new String(buf,0,len));
                buf=new byte[1024];
                len=fis.read(buf);
            }
            fis.close();
            etContent.setText(sb.toString());
            Toast.makeText(this, "读取成功", Toast.LENGTH_SHORT).show();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
